package com.yz.xyt.controller;

import com.yz.xyt.constant.HttpStatus;
import com.yz.xyt.domain.AppManager;
import com.yz.xyt.domain.ResponseResult;
import com.yz.xyt.service.IAppManagerService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 应用发布管理
 * @author JW.WANG
 */
@RestController
@RequestMapping("/app")
public class AppManagerController {

    @Autowired
    IAppManagerService appManagerService;

    /**
     * 应用上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public ResponseResult appUpload(MultipartFile file){
        ResponseResult result = new ResponseResult();
        result.setMsg("应用上传成功");
        result.setCode(HttpStatus.SUCCESS);
        int count = appManagerService.saveAppInfo(file);
        if (count == 0){
            result.setMsg("应用上传失败,文件已存在");
            result.setCode(HttpStatus.ERROR);
        }
        return result;
    }

    /**
     * 应用下载
     * @param appSuffix
     * @return
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> appDownload(String appSuffix){
        AppManager appManager = appManagerService.findAppVersion();
        String fileName = appManager.getAppName() + "." + appSuffix;

        String filePath = appManager.getPath() + "." + appSuffix;

        File file = new File(filePath);

        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type","application/vnd.android.package-archive");
        headers.set("Content-Disposition","attachment; filename=" + fileName);

        try {
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(new byte[0],headers, HttpStatus.ERROR);
        }
    }

}
